package cn.com.zpark.c3p0;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @PackageName: cn.com.zpark.c3p0
 * @ClassName: C3P0Utils01
 * @Description:C3P0数据库连接池
 * @author: RZS
 * @date: 2021/10/30  15:58
 */
public class C3P0Utils01 {

    // 数据源对象，作用：创建连接池
    private static DataSource dataSource;

    static {
        // 创建数据源对象
        dataSource = new ComboPooledDataSource();
    }


    /**
     * 获取数据库连接对象
     * @return
     */
    public static Connection getConn() throws SQLException {
        // 获取数据库连接对象
        return dataSource.getConnection();
    }

    /**
     * 关闭连接
     */
    public static void close(ResultSet res, Connection conn, Statement... stat){
        if(res != null){
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        /******************可变参数******************/
        Statement[] st = stat;
        for (int i = 0; i < st.length; i++) {
            if(st[i] != null){
                try {
                    st[i].close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        /******************可变参数******************/


        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
